/**
 * 
 */
package com.winit.openapi.fsp.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.SearchOperator;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.query.filter.SearchFilterHelper;
import com.winit.common.spi.context.CommandContext;
import com.winit.common.spring.SpringMessageLocator;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.erp.spi.product.ProductCategoryService;
import com.winit.erp.spi.product.TaxRuleService;
import com.winit.erp.spi.product.command.GetProductCategoryByBpartnerIdCommand;
import com.winit.erp.spi.product.command.GetProductCategoryByNameCommand;
import com.winit.erp.spi.product.vo.ProductCategory;
import com.winit.erp.spi.product.vo.TaxRule;
import com.winit.mms.spi.common.Constant;
import com.winit.mms.spi.goods.GoodsService;
import com.winit.mms.spi.goods.command.CreateGoodsCommand;
import com.winit.mms.spi.goods.command.GetGoodsByCodeAndSpecCommand;
import com.winit.mms.spi.goods.command.GetGoodsByCodesCommand;
import com.winit.mms.spi.goods.command.GetGoodsByGoodsIdCommand;
import com.winit.mms.spi.goods.command.GetGoodsListCommand;
import com.winit.mms.spi.goods.command.ImportFspGoodsCommand;
import com.winit.mms.spi.goods.command.QueryGoodsPageCommand;
import com.winit.mms.spi.goods.command.UpdateGoodsCommand;
import com.winit.mms.spi.goods.vo.BatchOptResult;
import com.winit.mms.spi.goods.vo.Customs;
import com.winit.mms.spi.goods.vo.Goods;
import com.winit.mms.spi.goods.vo.GoodsCertificate;
import com.winit.mms.spi.goods.vo.ImportFspGoodsErrMsg;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.fsp.utils.FspGoodsFieldValidator;
import com.winit.openapi.fsp.utils.GoodsConstant;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.ups.spi.basicdata.BasicDataService;
import com.winit.ups.spi.basicdata.command.GetBasicDataListCommand;
import com.winit.ups.spi.basicdata.vo.BasicData;

/**
 * fsp 金融商品
 * 
 * @author
 * @since 1.0
 */
@Controller
@RequestMapping(value = "/fsp/goods")
public class FSPGoodsInfoController extends BaseController {

	@Resource
	private GoodsService goodsService;

	@Resource
	private TaxRuleService taxRuleService;

	@Resource
	private ProductCategoryService productCategoryService;

	@Resource
	private BasicDataService basicDataService;

	/**
	 * 注册商品
	 * 
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 */
	@RequestMapping(value = "/create")
	public String create(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		Object obj = requestMsg.getData();
		CreateGoodsCommand command = null;
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			command = buildCreateGoodsInfoCommand(json);
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}
		goodsService.createGoods(command);
		return SUCCESS;
	}

	/**
	 * 修改商品
	 * 
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 */
	@RequestMapping(value = "/update")
	public String update(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		Object obj = requestMsg.getData();
		UpdateGoodsCommand command = null;

		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			command = buildUpdateGoodsCommand(json);
			CommandContext ctx = CommandContext.getContext();
			command.setCtx(ctx);
			Bpartner bpartner = (Bpartner) ctx.get(ApiConstant.API_BPARTNER);
			command.setWinitPartnerId(bpartner.getcBpartnerId());
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}

		// 调用接口更新信息
		goodsService.updateGoods(command);

		return SUCCESS;
	}

	/**
	 * 查询商品详情
	 * 
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 */
	@RequestMapping(value = "/query")
	public String query(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		Object obj = requestMsg.getData();
		GetGoodsByGoodsIdCommand command = null;
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			command = buildQueryGoodsByGoodsIdCommand(json);
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}

		Goods goods = goodsService.getGoodsByGoodsId(command);
		if (goods != null) {
			Map<String, Object> data = buildReturnGoodsMap(goods);
			responseMsg.setData(data);
		}

		return SUCCESS;
	}

	/**
	 * 根据条件查询金融商品
	 * 
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 */
	@RequestMapping(value = "/queryGoodsPageByCondition")
	public String queryGoodsPageByCondition(
			@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		Object obj = requestMsg.getData();
		CommandContext ctx = CommandContext.getContext();
		QueryGoodsPageCommand command = null;
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			validpageParams(json);
			command = new QueryGoodsPageCommand();
			command.setCtx(ctx);
			Bpartner bpartner = (Bpartner) ctx.get(ApiConstant.API_BPARTNER);
			Searchable searchable = buildSearchPageParams(json);
			searchable.and(SearchFilterHelper.newCondition("winit_partner_id",
					SearchOperator.eq, bpartner.getcBpartnerId()));
			searchable.and(SearchFilterHelper.newCondition("review_status",
					SearchOperator.ne, Constant.GoodStatus.RT));
			if (json.containsKey("winitClassifyCode")) {
				searchable.or(SearchFilterHelper.newCondition(
						"winit_classify_code", SearchOperator.like,
						"%" + json.getString("winitClassifyCode") + "%"));
			}
			if (json.containsKey("goodsCode")) {
				searchable.or(SearchFilterHelper.newCondition("goods_code",
						SearchOperator.like, "%" + json.getString("goodsCode")
								+ "%"));
			}
			if (json.containsKey("name")) {
				searchable
						.or(SearchFilterHelper.newCondition("cn_name",
								SearchOperator.like,
								"%" + json.getString("name") + "%"));

				searchable
						.or(SearchFilterHelper.newCondition("en_name",
								SearchOperator.like,
								"%" + json.getString("name") + "%"));
			}
			command.setSearchable(searchable);
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}
		command.setCtx(CommandContext.getContext());
		// 调用接口分页查询金融商品
		Page<Goods> pagelist = goodsService.queryGoodsPage(command);
		if (pagelist != null) {
			List<Map<String, Object>> datalist = buildReturnGoodsList(pagelist
					.getContent());
			Map<String, Object> pageMap = new HashMap<String, Object>();
			pageMap.put("pageNo", pagelist.getPageable().getPageNumber() + 1);
			pageMap.put("pageSize", pagelist.getPageable().getPageSize());
			pageMap.put("totalCount", pagelist.getTotalElements());
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("list", datalist);
			data.put("pageParams", pageMap);
			responseMsg.setData(data);
		}
		return SUCCESS;
	}

	/**
	 * 查询我的金融商品列表（分页）
	 * 
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 * @author BW
	 * @date 2015-3-16
	 */
	@RequestMapping(value = "queryGoodsPage")
	public String queryGoodsPage(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		Object obj = requestMsg.getData();
		CommandContext ctx = CommandContext.getContext();
		QueryGoodsPageCommand command = null;
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			validpageParams(json);
			command = new QueryGoodsPageCommand();
			command.setCtx(ctx);
			Bpartner bpartner = (Bpartner) ctx.get(ApiConstant.API_BPARTNER);
			Searchable searchable = buildSearchPageParams(json);
			searchable.and(SearchFilterHelper.newCondition("winit_partner_id",
					SearchOperator.eq, bpartner.getcBpartnerId()));
			command.setSearchable(searchable);
			command.setWinitPartnerId(bpartner.getcBpartnerId());
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}
		command.setCtx(CommandContext.getContext());
		// 调用接口分页查询金融商品
		Page<Goods> pagelist = goodsService.queryGoodsPage(command);
		if (pagelist != null) {
			List<Map<String, Object>> datalist = buildReturnGoodsList(pagelist
					.getContent());
			Map<String, Object> pageMap = new HashMap<String, Object>();
			pageMap.put("pageNo", pagelist.getPageable().getPageNumber() + 1);
			pageMap.put("pageSize", pagelist.getPageable().getPageSize());
			pageMap.put("totalCount", pagelist.getTotalElements());
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("list", datalist);
			data.put("pageParams", pageMap);
			responseMsg.setData(data);
		}
		return SUCCESS;
	}

	/**
	 * 查询金融商品列表（无分页）
	 * 
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 * @author BW
	 * @date 2015-3-16
	 */
	@RequestMapping(value = "getGoodsList")
	public String getGoodsList(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		Object obj = requestMsg.getData();
		GetGoodsListCommand command = null;
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			command = buildGetGoodsListCommand(json);
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}
		List<Goods> goodsList = goodsService.getGoodsList(command);
		if (goodsList != null) {
			List<Map<String, Object>> datalist = buildReturnGoodsList(goodsList);
			responseMsg.setData(datalist);
		}
		return SUCCESS;
	}

	private List<Map<String, Object>> buildReturnGoodsList(List<Goods> datalist) {
		List<Map<String, Object>> rslist = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		for (Goods goods : datalist) {
			map = buildReturnGoodsMap(goods);
			rslist.add(map);
		}
		return rslist;
	}

	private Searchable buildSearchPageParams(JSONObject json) {
		int pageNo = ApiConstant.PAGE_NO_DEFAULT;
		int pageSize = ApiConstant.PAGE_SIZE_DEFAULT;
		// pageParams
		if (json != null && json.containsKey("pageParams")) {
			JSONObject pageParams = json.getJSONObject("pageParams");
			// pageNo
			if (pageParams.containsKey("pageNo")) {
				pageNo = pageParams.getInteger("pageNo");
			}
			// pageSize
			if (pageParams.containsKey("pageSize")) {
				pageSize = pageParams.getInteger("pageSize");
			}
		}
		Searchable search = Searchable.newSearchable();
		search.setPage(pageNo - 1, pageSize);
		search.addSort(new Sort(Direction.DESC, "CREATED"));
		return search;
	}

	private void validpageParams(JSONObject json) {
		// pageParams
		if (json.containsKey("pageParams")) {
			Object obj = json.get("pageParams");
			if (obj instanceof JSONObject) {
				JSONObject pageParams = (JSONObject) obj;
				// pageNo
				ValidateUtil.validInteger(pageParams, "pageNo");
				// pageSize
				ValidateUtil.validInteger(pageParams, "pageSize");
				if (pageParams.containsKey("pageNo")) {
					int pageNo = pageParams.getInteger("pageNo");
					if (pageNo < 1) {
						throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
					}
				}
				if (pageParams.containsKey("pageSize")) {
					int pageSize = pageParams.getInteger("pageSize");
					if (pageSize < 1) {
						throw new ApiException(ErrorCode.FIELD_ERROR,
								"pageSize");
					}
				}
			} else {
				throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageParams");
			}
		}
	}

	private Map<String, Object> buildReturnGoodsMap(Goods goods) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", goods.getId());
		map.put("patentCertificateNumber", goods.getPatentCertificateNumber());
		map.put("isPatentCertificate", goods.getIsPatentCertificate());
		map.put("unit", goods.getUnit());
		map.put("brandCategoryId", goods.getBrandCategoryId());
		map.put("brandName", goods.getBrandName());
		map.put("cnName", goods.getCnName());
		map.put("color", goods.getColor());
		map.put("enName", goods.getEnName());
		map.put("exportPricesRmb", goods.getExportPricesRmb());
		map.put("exportPricesUsd", goods.getExportPricesUsd());
		map.put("goodsCode", goods.getGoodsCode());
		map.put("goodsLength", goods.getGoodsLength());
		map.put("goodsUse", goods.getGoodsUse());
		map.put("high", goods.getHigh());
		map.put("hsCode", goods.getHsCode());
		map.put("internetSite", goods.getInternetSite());
		map.put("isBattery", goods.getIsBattery());
		map.put("isSelfDeclaresth", goods.getIsSelfDeclaresth());
		map.put("isWholeSale", goods.getIsWholeSale());
		map.put("maintStatus", goods.getMaintStatus());
		map.put("material", goods.getMaterial());
		map.put("model", goods.getModel());
		map.put("overseasSales", goods.getOverseasSales());
		map.put("packageNumber", goods.getPackageNumber());
		map.put("packageMaterials", goods.getPackageMaterials());
		map.put("packageSize", goods.getPackageSize());
		map.put("photos", goods.getPhotos());
		map.put("rebateRate", goods.getRebateRate());
		map.put("reviewStatus", goods.getReviewStatus());
		map.put("sellerClassifyId", goods.getSellerClassifyId());
		map.put("species", goods.getSpecies());
		map.put("specification", goods.getSpecification());
		map.put("weight", goods.getWeight());
		map.put("wholeSaleDesc", goods.getWholeSaleDesc());
		map.put("width", goods.getWidth());
		map.put("winitClassifyCode", goods.getWinitClassifyCode());
		map.put("exportSeaport", goods.getExportSeaport());
		map.put("suggestion", goods.getSuggestion());
		map.put("isUpdate", goods.getIsUpdate());
		List<Map<String, Object>> cList = new ArrayList<Map<String, Object>>();
		Map<String, Object> customsMap = null;
		List<Customs> customsList = goods.getCustomsList();
		if (customsList != null) {
			for (Customs customs : customsList) {
				customsMap = new HashMap<String, Object>();
				customsMap.put("countryCode", customs.getCountryCode());
				customsMap.put("countryName", customs.getCountryName());
				customsMap.put("maintenanceStatus",
						customs.getMaintenanceStatus());
				customsMap.put("erpTag", customs.getErpTag());
				customsMap.put("value", customs.getValue());
				cList.add(customsMap);
			}
		}
		map.put("customsList", cList);

		List<Map<String, Object>> cerList = new ArrayList<Map<String, Object>>();
		Map<String, Object> certificateMap = null;
		List<GoodsCertificate> certificateList = goods.getCertificateList();
		if (certificateList != null) {
			for (GoodsCertificate certificate : certificateList) {
				certificateMap = new HashMap<String, Object>();
				certificateMap.put("certificateFileUrl",
						certificate.getCertificateFileUrl());
				certificateMap.put("certificateNo",
						certificate.getCertificateNo());
				certificateMap.put("certificateTypeCode",
						certificate.getCertificateTypeCode());
				certificateMap.put("id", certificate.getId());
				cerList.add(certificateMap);
			}
		}
		map.put("certificateList", cerList);

		return map;
	}

	private GetGoodsByGoodsIdCommand buildQueryGoodsByGoodsIdCommand(
			JSONObject json) {
		GetGoodsByGoodsIdCommand command = new GetGoodsByGoodsIdCommand();
		if (json.containsKey("goodsId")) {
			command.setGoodsId(json.getLong("goodsId"));
		}
		CommandContext ctx = CommandContext.getContext();
		command.setCtx(ctx);
		return command;
	}

	private GetGoodsListCommand buildGetGoodsListCommand(JSONObject json) {
		GetGoodsListCommand command = new GetGoodsListCommand();
		if (json.containsKey("winitPartnerId")) {
			command.setWinitPartnerId(json.getLong("winitPartnerId"));
		}
		if (json.containsKey("winitClassifyCode")) {
			command.setWinitClassifyCode(json.getString("winitClassifyCode"));
		}
		if (json.containsKey("goodsCode")) {
			command.setGoodsCode(json.getString("goodsCode"));
		}
		if (json.containsKey("name")) {
			command.setCnName(json.getString("name"));
		}
		if (json.containsKey("name")) {
			command.setEnName(json.getString("name"));
		}
		CommandContext ctx = CommandContext.getContext();
		command.setCtx(ctx);
		return command;
	}

	private CreateGoodsCommand buildCreateGoodsInfoCommand(JSONObject json) {
		CreateGoodsCommand command = new CreateGoodsCommand();
		CommandContext ctx = CommandContext.getContext();
		command.setCtx(ctx);
		Bpartner bpartner = (Bpartner) ctx.get(ApiConstant.API_BPARTNER);
		command.setWinitPartnerId(bpartner.getcBpartnerId());
		if (json.containsKey("patentCertificateNumber")) {
			command.setPatentCertificateNumber(json
					.getString("patentCertificateNumber"));
		}
		if (json.containsKey("isPatentCertificate")) {
			command.setIsPatentCertificate(json
					.getString("isPatentCertificate"));
		}
		if (json.containsKey("unit")) {
			command.setUnit(json.getString("unit"));
		}
		if (json.containsKey("brandCategoryId")) {
			command.setBrandCategoryId(json.getString("brandCategoryId"));
		}
		if (json.containsKey("brandName")) {
			command.setBrandName(json.getString("brandName"));
		}
		if (json.containsKey("cnName")) {
			command.setCnName(json.getString("cnName"));
		}
		if (json.containsKey("color")) {
			command.setColor(json.getString("color"));
		}
		if (json.containsKey("enName")) {
			command.setEnName(json.getString("enName"));
		}
		if (json.containsKey("exportPricesRmb")) {
			command.setExportPricesRmb(json.getBigDecimal("exportPricesRmb"));
		}
		if (json.containsKey("exportPricesUsd")) {
			command.setExportPricesUsd(json.getBigDecimal("exportPricesUsd"));
		}
		if (json.containsKey("goodsCode")) {
			command.setGoodsCode(json.getString("goodsCode"));
		}
		if (json.containsKey("goodsLength")) {
			command.setGoodsLength(json.getBigDecimal("goodsLength"));
		}
		if (json.containsKey("goodsUse")) {
			command.setGoodsUse(json.getString("goodsUse"));
		}
		if (json.containsKey("high")) {
			command.setHigh(json.getBigDecimal("high"));
		}
		if (json.containsKey("hsCode")) {
			command.setHsCode(json.getString("hsCode"));
		}
		if (json.containsKey("internetSite")) {
			command.setInternetSite(json.getString("internetSite"));
		}
		if (json.containsKey("isBattery")) {
			command.setIsBattery(json.getString("isBattery"));
		}
		if (json.containsKey("isSelfDeclaresth")) {
			command.setIsSelfDeclaresth(json.getString("isSelfDeclaresth"));
		}
		if (json.containsKey("isWholeSale")) {
			command.setIsWholeSale(json.getString("isWholeSale"));
		}
		if (json.containsKey("material")) {
			command.setMaterial(json.getString("material"));
		}
		if (json.containsKey("model")) {
			command.setModel(json.getString("model"));
		}
		if (json.containsKey("overseasSales")) {
			command.setOverseasSales(json.getBigDecimal("overseasSales"));
		}
		if (json.containsKey("packageNumber")) {
			if (!"".equals(json.getString("packageNumber"))) {
				command.setPackageNumber(json.getInteger("packageNumber"));
			}
		}
		if (json.containsKey("packageMaterials")) {
			command.setPackageMaterials(json.getString("packageMaterials"));
		}
		if (json.containsKey("packageSize")) {
			command.setPackageSize(json.getString("packageSize"));
		}
		if (json.containsKey("photos")) {
			command.setPhotos(json.getString("photos"));
		}
		if (json.containsKey("rebateRate")) {
			command.setRebateRate(json.getBigDecimal("rebateRate"));
		}
		if (json.containsKey("sellerClassifyId")) {
			command.setSellerClassifyId(json.getString("sellerClassifyId"));
		}
		if (json.containsKey("species")) {
			command.setSpecies(json.getString("species"));
		}
		if (json.containsKey("specification")) {
			command.setSpecification(json.getString("specification"));
		}
		if (json.containsKey("weight")) {
			command.setWeight(json.getBigDecimal("weight"));
		}
		if (json.containsKey("wholeSaleDesc")) {
			command.setWholeSaleDesc(json.getString("wholeSaleDesc"));
		}
		if (json.containsKey("winitClassifyCode")) {
			command.setWinitClassifyCode(json.getString("winitClassifyCode"));
		}
		if (json.containsKey("width")) {
			command.setWidth(json.getBigDecimal("width"));
		}
		if (json.containsKey("exportSeaport")) {
			command.setExportSeaport(json.getString("exportSeaport"));
		}
		List<Customs> customsList = new ArrayList<Customs>();
		Customs customs = null;
		if (json.containsKey("customsList")) {
			JSONArray packageList = json.getJSONArray("customsList");
			for (Object obj : packageList) {
				JSONObject pack = (JSONObject) obj;
				customs = new Customs();
				if (pack.containsKey("countryCode")) {
					customs.setCountryCode(pack.getString("countryCode"));
				}
				if (pack.containsKey("countryName")) {
					customs.setCountryName(pack.getString("countryName"));
				}
				if (pack.containsKey("value")) {
					customs.setValue(pack.getBigDecimal("value"));
				}
				customsList.add(customs);
			}
		}
		command.setCustomsList(customsList);

		List<GoodsCertificate> certificateList = new ArrayList<GoodsCertificate>();
		GoodsCertificate goodsCertificate = null;
		if (json.containsKey("certificateList")) {
			JSONArray packageList = json.getJSONArray("certificateList");
			for (Object obj : packageList) {
				JSONObject pack = (JSONObject) obj;
				goodsCertificate = new GoodsCertificate();
				if (pack.containsKey("certificateFileUrl")) {
					goodsCertificate.setCertificateFileUrl(pack
							.getString("certificateFileUrl"));
				}
				if (pack.containsKey("certificateNo")) {
					goodsCertificate.setCertificateNo(pack
							.getString("certificateNo"));
				}
				if (pack.containsKey("certificateTypeCode")) {
					goodsCertificate.setCertificateTypeCode(pack
							.getString("certificateTypeCode"));
				}
				certificateList.add(goodsCertificate);
			}
		}
		command.setCertificateList(certificateList);

		return command;
	}

	private UpdateGoodsCommand buildUpdateGoodsCommand(JSONObject json) {
		UpdateGoodsCommand command = new UpdateGoodsCommand();

		if (json.containsKey("goodsId")) {
			command.setGoodsId(json.getLong("goodsId"));
		}
		if (json.containsKey("patentCertificateNumber")) {
			command.setPatentCertificateNumber(json
					.getString("patentCertificateNumber"));
		}
		if (json.containsKey("isPatentCertificate")) {
			command.setIsPatentCertificate(json
					.getString("isPatentCertificate"));
		}
		if (json.containsKey("unit")) {
			command.setUnit(json.getString("unit"));
		}
		if (json.containsKey("brandCategoryId")) {
			command.setBrandCategoryId(json.getString("brandCategoryId"));
		}
		if (json.containsKey("brandName")) {
			command.setBrandName(json.getString("brandName"));
		}
		if (json.containsKey("cnName")) {
			command.setCnName(json.getString("cnName"));
		}
		if (json.containsKey("color")) {
			command.setColor(json.getString("color"));
		}
		if (json.containsKey("exportPricesRmb")) {
			command.setExportPricesRmb(json.getBigDecimal("exportPricesRmb"));
		}
		if (json.containsKey("exportPricesUsd")) {
			command.setExportPricesUsd(json.getBigDecimal("exportPricesUsd"));
		}
		if (json.containsKey("goodsLength")) {
			command.setGoodsLength(json.getBigDecimal("goodsLength"));
		}
		if (json.containsKey("goodsUse")) {
			command.setGoodsUse(json.getString("goodsUse"));
		}
		if (json.containsKey("high")) {
			command.setHigh(json.getBigDecimal("high"));
		}
		if (json.containsKey("hsCode")) {
			command.setHsCode(json.getString("hsCode"));
		}
		if (json.containsKey("internetSite")) {
			command.setInternetSite(json.getString("internetSite"));
		}
		if (json.containsKey("isBattery")) {
			command.setIsBattery(json.getString("isBattery"));
		}
		if (json.containsKey("isSelfDeclaresth")) {
			command.setIsSelfDeclaresth(json.getString("isSelfDeclaresth"));
		}
		if (json.containsKey("isWholeSale")) {
			command.setIsWholeSale(json.getString("isWholeSale"));
		}
		if (json.containsKey("reviewStatus")) {
			command.setReviewStatus(json.getString("reviewStatus"));
		}
		if (json.containsKey("material")) {
			command.setMaterial(json.getString("material"));
		}
		if (json.containsKey("material")) {
			command.setModel(json.getString("model"));
		}
		if (json.containsKey("overseasSales")) {
			command.setOverseasSales(json.getBigDecimal("overseasSales"));
		}
		if (json.containsKey("packageNumber")) {
			if (!"".equals(json.getString("packageNumber"))) {
				command.setPackageNumber(json.getInteger("packageNumber"));
			}
		}
		if (json.containsKey("packageMaterials")) {
			command.setPackageMaterials(json.getString("packageMaterials"));
		}
		if (json.containsKey("packageSize")) {
			command.setPackageSize(json.getString("packageSize"));
		}
		if (json.containsKey("photos")) {
			command.setPhotos(json.getString("photos"));
		}
		if (json.containsKey("rebateRate")) {
			command.setRebateRate(json.getBigDecimal("rebateRate"));
		}
		if (json.containsKey("reviewStatus")) {
			command.setReviewStatus(json.getString("reviewStatus"));
		}
		if (json.containsKey("sellerClassifyId")) {
			command.setSellerClassifyId(json.getString("sellerClassifyId"));
		}
		if (json.containsKey("species")) {
			command.setSpecies(json.getString("species"));
		}
		if (json.containsKey("weight")) {
			command.setWeight(json.getBigDecimal("weight"));
		}
		if (json.containsKey("wholeSaleDesc")) {
			command.setWholeSaleDesc(json.getString("wholeSaleDesc"));
		}
		if (json.containsKey("width")) {
			command.setWidth(json.getBigDecimal("width"));
		}
		if (json.containsKey("winitClassifyCode")) {
			command.setWinitClassifyCode(json.getString("winitClassifyCode"));
		}
		if (json.containsKey("exportSeaport")) {
			command.setExportSeaport(json.getString("exportSeaport"));
		}
		if (json.containsKey("isUpdate")) {
			if (!"".equals(json.getString("isUpdate"))) {
				command.setIsUpdate(json.getBoolean("isUpdate"));
			}

		}
		List<Customs> customsList = new ArrayList<Customs>();
		Customs customs = null;
		if (json.containsKey("customsList")) {
			JSONArray packageList = json.getJSONArray("customsList");
			for (Object obj : packageList) {
				JSONObject pack = (JSONObject) obj;
				customs = new Customs();
				if (pack.containsKey("countryCode")) {
					customs.setCountryCode(pack.getString("countryCode"));
				}
				if (pack.containsKey("countryName")) {
					customs.setCountryName(pack.getString("countryName"));
				}
				if (pack.containsKey("value")) {
					customs.setValue(pack.getBigDecimal("value"));
				}
				customsList.add(customs);
			}
		}
		command.setCustomsList(customsList);

		List<GoodsCertificate> certificateList = new ArrayList<GoodsCertificate>();
		GoodsCertificate goodsCertificate = null;
		if (json.containsKey("certificateList")) {
			JSONArray packageList = json.getJSONArray("certificateList");
			for (Object obj : packageList) {
				JSONObject pack = (JSONObject) obj;
				goodsCertificate = new GoodsCertificate();
				if (pack.containsKey("certificateFileUrl")) {
					goodsCertificate.setCertificateFileUrl(pack
							.getString("certificateFileUrl"));
				}
				if (pack.containsKey("certificateNo")) {
					goodsCertificate.setCertificateNo(pack
							.getString("certificateNo"));
				}
				if (pack.containsKey("certificateTypeCode")) {
					goodsCertificate.setCertificateTypeCode(pack
							.getString("certificateTypeCode"));
				}
				certificateList.add(goodsCertificate);
			}
		}
		command.setCertificateList(certificateList);

		return command;
	}

    /**
     * 批量导入金融产品
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     * @author BW
     * @date 2015-8-27
     */
    @RequestMapping(value = "/batchImportFspGoods")
    public String batchImportFspGoods(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        List<CreateGoodsCommand> goodsList = new ArrayList<CreateGoodsCommand>();
        List<ImportFspGoodsErrMsg> listErrMsg = new ArrayList<ImportFspGoodsErrMsg>();
        // 组装command
        ImportFspGoodsCommand command = new ImportFspGoodsCommand();
        command.setCtx(CommandContext.getContext());
        if (obj instanceof JSONArray) {
            JSONArray jsonarr = (JSONArray) obj;
            JSONArray jsonArrTmp = (JSONArray) jsonarr.clone();
            if (jsonarr.size() > 0) {
                if (jsonarr.size() > GoodsConstant.IMPORT_COUNT) {
                    throw new ApiException(ErrorCode.IMPORT_NUMBER_ERROR, jsonarr.size());
                }
                /** 获取所有退税率 */
                Map<String, TaxRule> rules = taxRuleService.queryCustomsTaxRule();
                // 获取所有品牌
                GetBasicDataListCommand brandCmd = new GetBasicDataListCommand();
                brandCmd.setCtx(CommandContext.getContext());
                brandCmd.setType(GetBasicDataListCommand.Type.brand.getVal());
                List<BasicData> listData = basicDataService.getBasicDataList(brandCmd);

                List<String> goodsCodes = new ArrayList<String>();
                for (int i = 0; i < jsonarr.size(); i++) {
                    JSONObject json = jsonarr.getJSONObject(i);
                    goodsCodes.add(json.getString("goodsCode"));
                }
                // 获取商品分类
                Bpartner bpartner = (Bpartner) CommandContext.getContext().get(ApiConstant.API_BPARTNER);
                GetGoodsByCodesCommand codesCommand = new GetGoodsByCodesCommand();
                codesCommand.setGoodsCodes(goodsCodes);
                codesCommand.setWinitPartnerId(bpartner.getcBpartnerId());
                List<Goods> goodsByCodesList = goodsService.getGoodsByCodes(codesCommand);

                GetProductCategoryByBpartnerIdCommand bpartnerIdCommand = new GetProductCategoryByBpartnerIdCommand();
                bpartnerIdCommand.setBpartnerId(bpartner.getcBpartnerId());
                List<ProductCategory> productCategoryList = productCategoryService.getProductCategoryByBpartnerId(bpartnerIdCommand);

                for (int i = 0; i < jsonarr.size(); i++) {
                    if (listErrMsg.size() >= GoodsConstant.IMPORT_COUNT) {
                        break;
                    }
                    JSONObject json = jsonarr.getJSONObject(i);
                    // 检验文件内金融商品是否重复
                    validFspGoodsIsRepeat(listErrMsg, json, jsonArrTmp, command);
                    // 校验输入参数
                    FspGoodsFieldValidator.validFspGoodsField(listErrMsg, json, command);
                    buildBrand(listData, json);
                    // 设置是否包含证书
                    bulidCertificate(json);
                    // 获取退税率
                    buildRebateRate(listErrMsg, command, rules, json);
                    // 检查数据库内是否存在重复的金融商品
                    validFspGoodsBiz(listErrMsg, json, command, goodsByCodesList);

                    bulidProductClassisfy(listErrMsg, json, productCategoryList, command);

                    // 插入商品
                    CreateGoodsCommand createCommand = new CreateGoodsCommand();
                    if (listErrMsg.size() == 0) {
                        createCommand = buildCreateGoodsInfoCommand(json);
                        goodsList.add(createCommand);
                    }
                }
            } else {
                throw new ApiException(ErrorCode.GOODS_NOT_NULL);
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        if (listErrMsg.size() != 0) {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("errMsg", listErrMsg);
            responseMsg.setData(data);
            return SUCCESS;
        }

		command.setGoodsList(goodsList);
		// 调用导入金融商品接口
		BatchOptResult result = goodsService.importFspGoods(command);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("errMsg", result.getErrMsg());
		responseMsg.setData(data);
		return SUCCESS;
	}

	/**
	 * 设置品牌ID
	 * @param listData
	 * @param json
	 * @author BW 
	 * @date 2015-9-9
	 */
	private void buildBrand(List<BasicData> listData, JSONObject json) {
		if (listData != null && listData.size() != 0) {
			for (int j = 0; j < listData.size(); j++) {
				if (listData.get(j).getCode()
						.equals(json.get("brandCategoryId"))) {
					json.put("brandCategoryId", listData.get(j).getId());
				}
			}
		}
	}

	/**
	 * 设置退税率
	 * 
	 * @param listErrMsg
	 * @param command
	 * @param rules
	 * @param json
	 */
	private void buildRebateRate(List<ImportFspGoodsErrMsg> listErrMsg,
			ImportFspGoodsCommand command, Map<String, TaxRule> rules,
			JSONObject json) {

		String hsCode = json.getString("hsCode");
		TaxRule rule = rules.get(hsCode);
		if (null == rule) {
			if (listErrMsg.size() < GoodsConstant.ERROR_COUNT) {
				ImportFspGoodsErrMsg msg = new ImportFspGoodsErrMsg(
						json.getString("lineNo"),
						SpringMessageLocator.getMessage(
								GoodsConstant.HS_CODE_NOT_FOUND, command
										.getCtx().getLocale()));
				listErrMsg.add(msg);
			}
		}
		// 将退税率暂存到json串中
		else {
			json.put("rebateRate", rule.getRaterebate());
		}
	}

	/**
	 * 设置是否为专利证书
	 * 
	 * @param json
	 * @author BW
	 * @date 2015-9-6
	 */
	private void bulidCertificate(JSONObject json) {
		
		// 判断专利证书号是否填写，如填写则给是否有专利证书字段赋值
		if (null != json.getString("patentCertificateNumber")
				&& !"".equals(json.getString("patentCertificateNumber"))) {
			json.put("isPatentCertificate", "Y");
		} else {
			json.put("isPatentCertificate", "N");
		}

	}

	/**
	 * 检验金融商品是否重复
	 * 
	 * @param listErrMsg
	 * @param json
	 * @param jsonarr
	 * @return 返回重复条数
	 * @author BW
	 * @date 2015-9-1
	 */
	private int validFspGoodsIsRepeat(List<ImportFspGoodsErrMsg> listErrMsg,
			JSONObject json, JSONArray jsonArrTmp, ImportFspGoodsCommand command) {
		String goodsCode = json.getString("goodsCode");
		String specification = json.getString("specification");
		JSONObject tmpJson = (JSONObject) json.clone();
		jsonArrTmp.remove(tmpJson);
		for (int i = 0; i < jsonArrTmp.size(); i++) {
			JSONObject json1 = jsonArrTmp.getJSONObject(i);
			if (goodsCode.equals(json1.getString("goodsCode"))
					&& specification.equals(json1.getString("specification"))) {
				if (listErrMsg.size() < GoodsConstant.ERROR_COUNT) {
					String errorMsg = SpringMessageLocator.getMessage(
							GoodsConstant.DATA_REPEAT,
							new String[] { json.getString("lineNo"),
									json1.getString("lineNo") }, command
									.getCtx().getLocale());
					ImportFspGoodsErrMsg msg = new ImportFspGoodsErrMsg(
							json.getString("lineNo"), errorMsg);
					listErrMsg.add(msg);
					jsonArrTmp.remove(json1);
				}
			}
		}
		return listErrMsg.size();
	}

	/**
	 * 检验业务
	 * 
	 * @param json
	 * @author BW
	 * @date 2015-8-31
	 */
	private int validFspGoodsBiz(List<ImportFspGoodsErrMsg> listErrMsg,
			JSONObject json, ImportFspGoodsCommand command) {
		if (listErrMsg.size() < GoodsConstant.ERROR_COUNT) {
			/** 验证商品是否重复 */
			String goodsCode = json.getString("goodsCode");
			String specification = json.getString("specification");
			GetGoodsByCodeAndSpecCommand gcommand = new GetGoodsByCodeAndSpecCommand();
			gcommand.setGoodsCode(goodsCode);
			gcommand.setSpecification(specification);
			Bpartner bpartner = (Bpartner) CommandContext.getContext().get(
					ApiConstant.API_BPARTNER);
			gcommand.setWinitPartnerId(bpartner.getcBpartnerId());
			Goods goods = goodsService.getGoodsByCodeSpecification(gcommand);
			if (goods != null) {
				if (listErrMsg.size() < GoodsConstant.ERROR_COUNT) {
					ImportFspGoodsErrMsg msg = new ImportFspGoodsErrMsg(
							json.getString("lineNo"),
							SpringMessageLocator.getMessage(
									GoodsConstant.GOODS_IS_EXISTS, command
											.getCtx().getLocale()));
					listErrMsg.add(msg);
				} else {
					return listErrMsg.size();
				}
			}
			return listErrMsg.size();
		}
		return listErrMsg.size();
	}

    private void validFspGoodsBiz(List<ImportFspGoodsErrMsg> listErrMsg, JSONObject json,
                                  ImportFspGoodsCommand command, List<Goods> goodsByCodesList) {
        if (goodsByCodesList != null && goodsByCodesList.size() > 0 && listErrMsg.size() < GoodsConstant.ERROR_COUNT) {
            /** 验证商品是否重复 */
            String goodsCode = json.getString("goodsCode");
            String specification = json.getString("specification");
            for (Goods goods : goodsByCodesList) {
                if (goods != null) {
                    if (goods.getGoodsCode().equals(goodsCode) && goods.getSpecification().equals(specification)) {
                        ImportFspGoodsErrMsg msg = new ImportFspGoodsErrMsg(json.getString("lineNo"),
                            SpringMessageLocator.getMessage(GoodsConstant.GOODS_IS_EXISTS, command.getCtx().getLocale()));
                        listErrMsg.add(msg);
                    }
                }
            }
        }
    }

    private void bulidProductClassisfy(List<ImportFspGoodsErrMsg> listErrMsg, JSONObject json,
                                       List<ProductCategory> productCategoryList, ImportFspGoodsCommand command) {
        /** 获取卖家分类 */
        Long sellerClassifyId = 0L;
        // 一级分类
        String sellerClassifyId1 = json.getString("sellerClassifyId1");
        // 二级分类
        String sellerClassifyId2 = json.getString("sellerClassifyId2");
        // 三级分类
        String sellerClassifyId3 = json.getString("sellerClassifyId3");
        /** 一级分类 */
        int i = 0;
        Long tmpSellerClassifyId1 = 0L;
        for (ProductCategory p : productCategoryList) {
            if ((null == p.getProductCategoryParentId()) && sellerClassifyId1.equals(p.getName())) {
                tmpSellerClassifyId1 = p.getProductCategoryId();
                sellerClassifyId = p.getProductCategoryId();
                i++;
            }
        }
        if (tmpSellerClassifyId1.longValue() == 0L || i > 1) {
            if (listErrMsg.size() < GoodsConstant.ERROR_COUNT) {
                ImportFspGoodsErrMsg msg = new ImportFspGoodsErrMsg(json.getString("lineNo"),
                    SpringMessageLocator.getMessage(GoodsConstant.SELLER_CLASSIFY1_ERROR, command.getCtx().getLocale()));
                listErrMsg.add(msg);
            }
        }
        /** 二级分类 */
        Long tmpSellerClassifyId2 = 0L;
        if (null != sellerClassifyId2 && !"".equals(sellerClassifyId2)) {
            for (ProductCategory p : productCategoryList) {
                if (null != p.getProductCategoryParentId()) {
                    if (sellerClassifyId.compareTo(p.getProductCategoryParentId()) == 0
                        && sellerClassifyId2.equals(p.getName())) {
                        tmpSellerClassifyId2 = p.getProductCategoryId();
                        sellerClassifyId = p.getProductCategoryId();
                        break;
                    }
                }
            }
            if (tmpSellerClassifyId2.longValue() == 0L) {
                if (listErrMsg.size() < GoodsConstant.ERROR_COUNT) {
                    ImportFspGoodsErrMsg msg = new ImportFspGoodsErrMsg(json.getString("lineNo"),
                        SpringMessageLocator.getMessage(GoodsConstant.SELLER_CLASSIFY2_ERROR, command.getCtx()
                            .getLocale()));
                    listErrMsg.add(msg);
                }

            }
        }
        /** 三级分类 */
        Long tmpSellerClassifyId3 = 0L;
        if (null != sellerClassifyId2 && !"".equals(sellerClassifyId2) && null != sellerClassifyId3
            && !"".equals(sellerClassifyId3)) {
            for (ProductCategory p : productCategoryList) {
                if (null != p.getProductCategoryParentId()) {
                    if (sellerClassifyId.compareTo(p.getProductCategoryParentId()) == 0
                        && sellerClassifyId3.equals(p.getName())) {
                        tmpSellerClassifyId3 = p.getProductCategoryId();
                        sellerClassifyId = p.getProductCategoryId();
                        break;
                    }
                }
            }
            if (tmpSellerClassifyId3.longValue() == 0L) {
                if (listErrMsg.size() < GoodsConstant.ERROR_COUNT) {
                    ImportFspGoodsErrMsg msg = new ImportFspGoodsErrMsg(json.getString("lineNo"),
                        SpringMessageLocator.getMessage(GoodsConstant.SELLER_CLASSIFY3_ERROR, command.getCtx()
                            .getLocale()));
                    listErrMsg.add(msg);
                }

            }
        }
        json.put("sellerClassifyId", sellerClassifyId);
    }

    /***
     * 检查卖家分类
     * 
     * @param json
     * @param bpartner
     * @author BW
     * @date 2015-8-31
     */
    private int checkProductClassify(List<ImportFspGoodsErrMsg> listErrMsg, JSONObject json, Bpartner bpartner,
                                     ImportFspGoodsCommand command) {
        /** 获取卖家分类 */
        Long sellerClassifyId = 0L;
        // 一级分类
        String sellerClassifyId1 = json.getString("sellerClassifyId1");
        // 二级分类
        String sellerClassifyId2 = json.getString("sellerClassifyId2");
        // 三级分类
        String sellerClassifyId3 = json.getString("sellerClassifyId3");
        /** 一级分类 */
        GetProductCategoryByNameCommand catCommand1 = new GetProductCategoryByNameCommand();
        catCommand1.setBpartnerId(bpartner.getcBpartnerId());
        catCommand1.setName(sellerClassifyId1);
        List<ProductCategory> productCategoryList1 = productCategoryService.getProductCategoryByName(catCommand1);
        if (null == productCategoryList1 || productCategoryList1.size() == 0 || productCategoryList1.size() > 1) {
            if (listErrMsg.size() < GoodsConstant.ERROR_COUNT) {
                ImportFspGoodsErrMsg msg = new ImportFspGoodsErrMsg(json.getString("lineNo"),
                    SpringMessageLocator.getMessage(GoodsConstant.SELLER_CLASSIFY1_ERROR, command.getCtx().getLocale()));
                listErrMsg.add(msg);
            } else {
                return listErrMsg.size();
            }
        } else {
            sellerClassifyId = productCategoryList1.get(0).getProductCategoryId();
        }
        /** 二级分类 */
        if (null != sellerClassifyId2 && !"".equals(sellerClassifyId2)) {
            GetProductCategoryByNameCommand catCommand2 = new GetProductCategoryByNameCommand();
            catCommand2.setBpartnerId(bpartner.getcBpartnerId());
            catCommand2.setName(sellerClassifyId2);
            catCommand2.setCategoryParentId(sellerClassifyId);
            List<ProductCategory> productCategoryList2 = productCategoryService.getProductCategoryByName(catCommand2);
            if (null == productCategoryList2 || productCategoryList2.size() == 0 || productCategoryList2.size() > 1) {
                if (listErrMsg.size() < GoodsConstant.ERROR_COUNT) {
                    ImportFspGoodsErrMsg msg = new ImportFspGoodsErrMsg(json.getString("lineNo"),
                        SpringMessageLocator.getMessage(GoodsConstant.SELLER_CLASSIFY2_ERROR, command.getCtx()
                            .getLocale()));
                    listErrMsg.add(msg);
                } else {
                    return listErrMsg.size();
                }
            } else {
                if (sellerClassifyId.compareTo(productCategoryList2.get(0).getProductCategoryParentId()) == 0) {
                    sellerClassifyId = productCategoryList2.get(0).getProductCategoryId();
                } else {
                    if (listErrMsg.size() < GoodsConstant.ERROR_COUNT) {
                        ImportFspGoodsErrMsg msg = new ImportFspGoodsErrMsg(json.getString("lineNo"),
                            SpringMessageLocator.getMessage(GoodsConstant.SELLER_CLASSIFY2_ERROR, command.getCtx()
                                .getLocale()));
                        listErrMsg.add(msg);
                    } else {
                        return listErrMsg.size();
                    }
                }
            }
        }
        /** 三级分类 */
        if (null != sellerClassifyId2 && !"".equals(sellerClassifyId2) && null != sellerClassifyId3
            && !"".equals(sellerClassifyId3)) {
            GetProductCategoryByNameCommand catCommand3 = new GetProductCategoryByNameCommand();
            catCommand3.setBpartnerId(bpartner.getcBpartnerId());
            catCommand3.setName(sellerClassifyId3);
            catCommand3.setCategoryParentId(sellerClassifyId);
            List<ProductCategory> productCategoryList3 = productCategoryService.getProductCategoryByName(catCommand3);
            if (null == productCategoryList3 || productCategoryList3.size() == 0 || productCategoryList3.size() > 1) {
                if (listErrMsg.size() < GoodsConstant.ERROR_COUNT) {
                    ImportFspGoodsErrMsg msg = new ImportFspGoodsErrMsg(json.getString("lineNo"),
                        SpringMessageLocator.getMessage(GoodsConstant.SELLER_CLASSIFY3_ERROR, command.getCtx()
                            .getLocale()));
                    listErrMsg.add(msg);
                } else {
                    return listErrMsg.size();
                }
            } else {
                if (sellerClassifyId.compareTo(productCategoryList3.get(0).getProductCategoryParentId()) == 0) {
                    sellerClassifyId = productCategoryList3.get(0).getProductCategoryId();
                }
            }
        }
        json.put("sellerClassifyId", sellerClassifyId);
        return listErrMsg.size();
    }
}
